package com.concurrent.blockingq;

import java.util.concurrent.BlockingQueue;

public class BQConsumer implements Runnable{

	private Thread thread;
	private String name;
	private BlockingQueue<String> q;
	private long timeToSleep;
	
	public BQConsumer(String name, BlockingQueue<String> q, long timeToSleep){
		this.name = name;
		this.q = q;
		this.timeToSleep = timeToSleep;
		
		thread = new Thread(this, name);
	}
	
	public void start(){
		thread.start();
	}
	
	public void run(){
	
		while(true){
			try {
				System.out.println(name + ": trying to consume");
				
				//remove method throw exception if queue is empty, hence using poll
				String item = q.poll();
				if(item == null){
					long start = System.currentTimeMillis();  

					//poll is non blocking, that's why using take
					item = q.take();
					System.out.println(name + ": It seems Producer is slow. Consumer waited for "  
					+ (System.currentTimeMillis() - start)  
					+ "ms");  
				}
				System.out.println(name + ": consumed : " + item);
				Thread.sleep(timeToSleep);
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
	}
}